//
//  ChooseRelationViewController.m
//  leo
//
//  Created by 常艳 on 15/11/6.
//  Copyright (c) 2015年 mdx. All rights reserved.
//

#import "ChooseRelationViewController.h"
#import "RelationCollectionViewCell.h"
#import "LeoMsg.h"
#import "BindViewController.h"
#import "SyncManager.h"
#import "SetBabyInfoViewController.h"
#import "AppDelegate.h"
@interface ChooseRelationViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UIAlertViewDelegate>
@property(nonatomic,strong) NSArray *relationData;
@property(nonatomic,strong) NSArray *relationPic;
@property(nonatomic,assign) BOOL isRegis;
@property(nonatomic,strong) RelationCollectionViewCell * selectCell;
@property(nonatomic,strong) NSString *relationStr;
@property(nonatomic,assign) float rate;
@end

@implementation ChooseRelationViewController
-(void)dealloc
{
    self.relationData=NULL;
    self.relationPic=NULL;
    self.selectCell=NULL;
    self.relationStr=NULL;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    float mainWidth=[UIScreen mainScreen].bounds.size.width;
    self.rate=mainWidth/320;
    self.extendedLayoutIncludesOpaqueBars=YES;
    self.title=@"请选择关系";
    UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Back_icon@2x.png"] style:UIBarButtonItemStylePlain target:self action:@selector(goback)];
    [self.navigationItem setLeftBarButtonItem:leftButton];
    self.relationData=[[NSArray alloc] initWithObjects:@"爸爸",@"妈妈",@"爷爷",@"奶奶",@"外公",@"外婆",@"哥哥",@"姐姐",@"自定义", nil];
    self.relationPic=[[NSArray alloc] initWithObjects:@"avater_man@2x.png",@"avater_woman@2x.png",@"avater_grandpa@2x.png",@"avater_grandma.png",@"avater_grandpa@2x.png",@"avater_grandma.png",@"avater_brother.png",@"avater_sister@2x.png",@"avater_other@2x_round.png", nil];
    self.relationStr=@"爸爸";

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if(self.view.window==nil)
    {
        self.view=nil;
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.relationData.count;
    
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString * CellIdentifier = @"RelationCollectionViewCell";
    if(!self.isRegis)
    {
        [collectionView registerNib:[UINib nibWithNibName:@"RelationCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:CellIdentifier];
        self.isRegis=YES;
    }
    RelationCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    if(cell==NULL)
    {
        NSLog(@"%@,cellForItemAtIndexPath,cell is null.",Relation_tag);
        return cell;
    }
    else
    {
        NSString *name=[self.relationData objectAtIndex:[indexPath row]];
        if(name!=NULL)
        {
            cell.nameLable.text=name;
        }
        cell.img.image=[UIImage imageNamed:[self.relationPic objectAtIndex:[indexPath row]]];
    }
    if([indexPath row]==0)
    {
        cell.avaterBg.hidden=NO;
        self.selectCell=cell;
    }
    return cell;
}
#pragma mark --UICollectionViewDelegateFlowLayout
//定义每个UICollectionView 的大小

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGRect rect=[[UIScreen mainScreen] bounds];
    CGSize size=rect.size;
    float width=(size.width-40*self.rate)/2;
    float height=width*0.55;
    if([indexPath row]==self.relationData.count-1)
    {
        width=(size.width-40*self.rate);
    }
    return CGSizeMake(width, height);
}
//定义每个UICollectionView 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(13*self.rate, 10*self.rate, 13*self.rate, 10*self.rate);
}
#pragma mark --UICollectionViewDelegate
//UICollectionView被选中时调用的方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if(self.selectCell!=NULL)
    {
        self.selectCell.avaterBg.hidden=YES;
    }
    RelationCollectionViewCell *cell = (RelationCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    cell.avaterBg.hidden=NO;
    self.selectCell=cell;
    NSInteger row=[indexPath row];
    if(row==([self.relationData count]-1))
    {
        self.relationStr=NULL;
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"请输入关系"
                                                        message:nil
                                                       delegate:self
                                              cancelButtonTitle:@"取消"
                                              otherButtonTitles:@"确定", nil];
        // 基本输入框，显示实际输入的内容
        alert.alertViewStyle = UIAlertViewStylePlainTextInput;
        //设置输入框的键盘类型
        UITextField *nickTextField = [alert textFieldAtIndex:0];
        nickTextField.keyboardType = UIKeyboardTypeDefault;
        [nickTextField addTarget:self action:@selector(relationTextFieldChange:) forControlEvents:UIControlEventEditingChanged];
        [alert show];
        alert=NULL;
    }
    else
    {
        self.relationStr=[self.relationData objectAtIndex:[indexPath row]];
    }
}
- (void)relationTextFieldChange:(UITextField *)textField
{
    if (textField.text.length > 10) {
        textField.text = [textField.text substringToIndex:10];
    }
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(buttonIndex==1)
    {
        // 取得输入的值
        UITextField *relationTextField = [alertView textFieldAtIndex:0];
        NSString* relation = [relationTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
        if([relation isEqualToString:@""]||[relation length]<=0)
        {
            [LeoMsg showMsg:@"关系不能为空"];
        }
        else if([Tooler checkStringIllegal:relation ChnLength:6 EngLength:10]==1)
        {
            [LeoMsg showMsg:@"关系名称不合法"];
        }
        else if([Tooler checkStringIllegal:relation ChnLength:6 EngLength:10]==2)
        {
            [LeoMsg showMsg:@"关系名称太长，中文字符只能输入6个，英文字符最多10个"];
        }
        else
        {
            self.relationStr=relation;
            self.selectCell.nameLable.text=relation;
        }
    }

}
//返回这个UICollectionView是否可以被选择
-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (IBAction)next:(id)sender {
    self.nextBtn.enabled=NO;
    if(self.relationStr==NULL||[self.relationStr isEqualToString:@""])
    {
        [LeoMsg showMsg:@"请选择或输入关系"];
        self.nextBtn.enabled=YES;
        return;
    }
    //调用API进行绑定
    SyncManager *syncManager=[[SyncManager alloc] init];
    [syncManager bindDevice:self.watch.deviceUid bindCode:self.watch.bindCode  alias:self.relationStr completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
        if(result==SUCESS)//绑定成功
        {
            int groupId=0;
            if(retValue!=NULL)
            {
                groupId=[[retValue valueForKey:@"groupId"] intValue];
            }
            if(groupId>0)//如果手表第一次被绑定，跳转设置宝宝信息界面
            {
                SetBabyInfoViewController *setBaby=[[SetBabyInfoViewController alloc] init];
                setBaby.watch=self.watch;
                UINavigationController *setBabyNav=[[UINavigationController alloc] initWithRootViewController:setBaby];
                AppDelegate *mydelegate=[[UIApplication sharedApplication] delegate];
                if(mydelegate!=NULL)
                {
                    [mydelegate setNavProperty:setBabyNav];
                    mydelegate.isAdmin=YES;
                }
                self.view.window.rootViewController=setBabyNav;
                setBaby=NULL;
                [self.navigationController popToRootViewControllerAnimated:YES];
            }
            else//副管理员绑定，跳转等待确认界面
            {
                if(self.type==2)//drop
                {
                    [LeoMsg showToastMsg:@"绑定请求已发送，请等待主管理员确认" parentView:self.navigationController.view showPosition:TOAST_SHOW_MID hideAfterDelay:1];
                    [self.navigationController popToRootViewControllerAnimated:YES];
                }
                else if(self.type==3||self.type==1)//family bind
                {
                    BindViewController *bindView=[[BindViewController alloc] init];
                    bindView.type=2;
                    UINavigationController *bindNav=[[UINavigationController alloc] initWithRootViewController:bindView];
                    AppDelegate *mydelegate=[[UIApplication sharedApplication] delegate];
                    if(mydelegate!=NULL)
                        [mydelegate setNavProperty:bindNav];
                    self.view.window.rootViewController=bindNav;
                    bindView=NULL;
                    [self.navigationController popToRootViewControllerAnimated:YES];
                }

            }
        }
        else//绑定失败，跳转重新绑定界面
        {
            [Tooler showHttpMsg:result description:description msg:@"绑定发生错误，请重新扫码绑定"];
            self.nextBtn.enabled=YES;
            //[self goback];
        }
    }];
}
-(void)goback
{
    if(self.type==1)//bind
    {
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
    else if(self.type==2)//drop
    {
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
    else if(self.type==3)//family
    {
        [self.navigationController popToRootViewControllerAnimated:YES];
        BindViewController *bindView=[[BindViewController alloc] init];
        UINavigationController *bindNav=[[UINavigationController alloc] initWithRootViewController:bindView];
        AppDelegate *mydelegate=[[UIApplication sharedApplication] delegate];
        if(mydelegate!=NULL)
            [mydelegate setNavProperty:bindNav];
        self.view.window.rootViewController=bindNav;
        bindView=NULL;
    }

}
@end
